import React, { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

const VirtualList = ({
    data = [],          // 数据源
    itemHeight = 50,    // 每项高度(固定高度)
    containerHeight = 500, // 容器高度
    bufferSize = 5,     // 缓冲数量
}) => {
    // 数据源应该从哪开始渲染
    const [startIndex, setStartIndex] = useState(0);
    // 绑定dom元素，用于计算滚动位置
    const containerRef = useRef(null);

    // 计算可见项数量一屏能显示多少项
    const visibleCount = Math.ceil(containerHeight / itemHeight) + bufferSize;
    // 计算渲染结束的位置，不能超过数据总长度
    const endIndex = Math.min(startIndex + visibleCount, data.length);

    // 计算总高度(用于撑开容器)
    const totalHeight = data.length * itemHeight;

    // 计算偏移量(用于定位可见项)
    const offsetY = startIndex * itemHeight;

    // 可见的数据项，截取可见的数据
    const visibleData = data.slice(startIndex, endIndex);

    // 滚动事件处理
    const handleScroll = () => {
        if (containerRef.current) {
            const scrollTop = containerRef.current.scrollTop;//获取顶部滚动出去的距离
            const newStartIndex = Math.floor(scrollTop / itemHeight);//向下取整，计算当前滚动到了第几项，就从第几项开始显示
            setStartIndex(Math.max(0, newStartIndex - bufferSize));//更新状态
        }
    };

    const nav = useNavigate();
    // 点击跳转详情页
    const handleItemdetail =(id)=>{
        console.log("跳转详情页",id);
        nav(`/detail?id=${id}`)
    }

    return (
        <div
            ref={containerRef}
            style={{
                height: containerHeight,
                overflow: 'auto',
                position: 'relative',
                // border: '1px solid #ddd',
            }}
            onScroll={handleScroll}
        >
            <div style={{ height: totalHeight }}>
                <div
                    style={{
                        position: 'absolute',
                        top: offsetY,
                        left: 0,
                        right: 0,
                    }}
                >
                    {visibleData.map((item, index) => (
                        <div
                            key={item.id || `item-${startIndex + index}`}
                            style={{ height: itemHeight, display: 'flex', borderBottom: 'solid 1px #e7e7e7', padding: '10px' }}
                            onClick={() => handleItemdetail(item.id)}
                        >
                            <div style={{ fontSize: '16px', flex: 1 }}>{item.title}</div>
                            <img style={{ width: '100px' }} src={item.thumbnail} alt={item.title} />
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default VirtualList;